<template>
  <div class="complaint-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">投诉信息管理系统</h1>
	            <p class="sub-title">不推诿每一份意见，不怠慢每一次投诉，以真诚回应需求，用行动守护信任</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="投诉详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="投诉信息" direction="vertical" :column="4" :model="messageForm" border>
        <el-descriptions-item label="投诉ID" :span="2">{{ messageForm.id }}</el-descriptions-item>
        <el-descriptions-item label="标题" :span="2">{{ messageForm.title }}</el-descriptions-item>
        <el-descriptions-item label="投诉内容" :span="2">{{ messageForm.content }}</el-descriptions-item>
        <el-descriptions-item label="投诉状态" :span="2">{{ messageForm.complaintStatus }}</el-descriptions-item>
        <el-descriptions-item label="投诉人ID" :span="2">{{ messageForm.complainantId }}</el-descriptions-item>
        <el-descriptions-item label="处理人" :span="2">{{ messageForm.handler }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑投诉"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="投诉内容" prop="content">
              <el-input type="textarea" v-model="ruleForm.content"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投诉人ID" prop="complainantId">
              <el-input v-model="ruleForm.complainantId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="投诉状态" prop="complaintStatus">
          <el-select v-model="ruleForm.complaintStatus" placeholder="请选择投诉状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="ruleForm.handler"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定修改</el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogVisible2"
      title="新增投诉"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投诉ID" prop="id">
              <el-input v-model="addForm.id"></el-input>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="addForm.title"></el-input>
            </el-form-item>
            <el-form-item label="投诉内容" prop="content">
              <el-input type="textarea" v-model="addForm.content"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投诉人ID" prop="complainantId">
              <el-input v-model="addForm.complainantId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="投诉状态" prop="complaintStatus">
          <el-select v-model="addForm.complaintStatus" placeholder="请选择投诉状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="addForm.handler"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">确定添加</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 显示表界面 -->
    <el-row style="width: 100%;">
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px;">
        <el-col :span="6">
          <el-input 
            placeholder="输入标题查询" 
            v-model="Condition.searchQuery" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="Condition.selectedCategory" 
            placeholder="选择投诉状态" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            icon="el-icon-plus" 
            @click="openDetails2" 
            style="width: 100%;"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
      
      <el-table 
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="id" label="投诉ID" width="160" align="center"></el-table-column>
        <el-table-column prop="title" label="标题" width="160" align="center"></el-table-column>
        <el-table-column prop="content" label="投诉内容" width="300" align="center"></el-table-column>
        <el-table-column prop="complaintStatus" label="投诉状态" width="140" align="center"></el-table-column>
        <el-table-column prop="complainantId" label="投诉人ID" width="250" align="center"></el-table-column>
        <el-table-column prop="handler" label="处理人" width="160" align="center"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetails(scope.row)">查看</el-button>
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="openDetails1(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

// 对话框控制变量
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)

// 搜索条件
const Condition = reactive({
  searchQuery: '',
  selectedCategory: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 表单引用
const ruleFormRef = ref(null)
const addFormRef = ref(null)

// 详情表单数据
const messageForm = reactive({
  id: '',
  title: '',
  content: '',
  complaintStatus: '',
  complainantId: '',
  handler: ''
})

// 编辑表单数据
const ruleForm = reactive({
  id: '',
  title: '',
  content: '',
  complaintStatus: '',
  complainantId: '',
  handler: ''
})

// 新增表单数据
const addForm = reactive({
  id: '',
  title: '',
  content: '',
  complaintStatus: '',
  complainantId: '',
  handler: ''
})

// 表单验证规则
const rules = reactive({
  id: [
    { required: true, message: '请输入投诉ID', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入投诉内容', trigger: 'blur' }
  ],
  complainantId: [
    { required: true, message: '请输入投诉人ID', trigger: 'blur' }
  ],
  complaintStatus: [
    { required: true, message: '请选择投诉状态', trigger: 'change' }
  ]
})

// 打开详情对话框
function openDetails(row) {
  dialogVisible.value = true
  Object.assign(messageForm, row)
}

// 打开编辑对话框
function openDetails1(row) {
  dialogVisible1.value = true
  // 深拷贝行数据到表单
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = row[key] ?? ''
  })
}

// 打开新增对话框
function openDetails2() {
  dialogVisible2.value = true
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = ''
  })
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 分页大小改变
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页改变
function handleCurrentChange(val) {
  currentPage.value = val
}

// 提交编辑表单
function submitForm() {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return

    const loading = ElLoading.service({ text: '修改中...' })
    post('/sc/complaint/updateById', ruleForm, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('修改成功！')
        dialogVisible1.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '修改失败')
      }
    })
  })
}

// 处理新增
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (!valid) return

    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/complaint/add', addForm, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('添加成功！')
        dialogVisible2.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 处理删除
function handleDelete(row) {
  ElMessageBox.confirm(`确定删除投诉 ${row.title} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/complaint/deleteById', { id: row.id }, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('删除成功！')
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 搜索投诉
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  post('/sc/complaint/byStatus', {
    status: Condition.selectedCategory,
    title: Condition.searchQuery
  }, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success(`找到 ${res.data.length} 条记录`)
    } else {
      tableData.value = []
      ElMessage.warning('未找到匹配记录')
    }
  })
}

// 获取所有投诉数据
function fetchTableData() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/complaint/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  })
}

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.complaint-container {
  width: 100%; /* 改为100%，确保最外层占满父容器 */
  box-sizing: border-box; /* 可选：防止padding影响宽度计算 */
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

.el-form-item .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}
</style>